import {
	sub
} from '@/common/event.js'
import store from '../index.js'
import moment from 'moment'
import {
	getRqst
} from '../../common/request'

export default {
	namespaced: true,
	state: {
		list: []
	},
	mutations: {
		setPyqlist: (state, payload) => {
			state.list = payload
		},
		delpyqinfo: (state, payload) => {
			state.list.filter(e => e.id != payload.id)
		},
		addpyqinfo: (state, payload) => {
			if (payload.type == '好友') {
				const list = store.state.friend.list
				for (let o of list) {
					if (o.fid == payload.uid) {
						state.list.unshift(payload)
						break
					}
				}
			} else if (payload.type == '公开') {
				state.list.unshift(payload)
			}
		},
	},
	actions: {
		async init({
			commit,
			state
		}, {
			payload
		}) {
			const n = moment().valueOf()
			const ret = await getRqst().get(`friend/friend/getpyqlist/${n}`)
			if (ret && ret.success && ret.data && ret.data.length > 0) {
				commit(`setPyqlist`, ret.data)
			}
		},
		async getmorepyqinfo({
			commit,
			state
		}, {
			payload
		}) {
			const n = payload.time
			const ret = await getRqst().get(`friend/friend/getpyqlist/${n}`)
			if (ret && ret.success && ret.data && ret.data.length > 0) {
				commit(`setPyqlist`, ret.data)
			}
		},

	},
	init: async function() {
		console.log("pyq初始化")

		const user = uni.getStorageSync("user")
		if (user && user.id) {
			store.dispatch({
				type: "pyq/init",
				payload: {}
			})
		}

		sub("loginSuccess", () => {
			store.dispatch({
				type: "pyq/init",
				payload: {}
			})
		})

		sub("socket_addpyqinfo", (e) => {
			if (e.type != '私有') {
				store.commit("pyq/addpyqinfo", e)
			}
		})

		sub("socket_delpyqinfo", (e) => {
			store.commit("pyq/delpyqinfo", e)
		})


	}
}